package edu.spec.chenli.Servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.*;

@WebServlet(name = "Ts",urlPatterns = {"/ts"},initParams = {@WebInitParam(name="driver",value = "com.mysql.jdbc.Driver"),
  @WebInitParam(name="url",value = "jdbc:mysql://localhost:3306/1613580007_1"),
  @WebInitParam(name="user",value = "root"),
  @WebInitParam(name = "pass",value = "123456789")})
public class TestServlet extends HttpServlet {
    //重写init方法

    @Override
    public void init(ServletConfig config) throws ServletException {
       //重写该方法，应该首先调用父类的init方法
        super.init(config);
    }
      //响应客户请求的方法
    public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
        //获取servletConfig对象
        ServletConfig config = getServletConfig();
        String driver = config.getInitParameter("driver");
        String url = config.getInitParameter("url");
        String user = config.getInitParameter("user");
        String pass = config.getInitParameter("pass");
        //注册驱动
        try {
            Class.forName(driver);
            //获取数据库连接
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement stmt = conn.createStatement();
            //执行查询，获取ResultSet
            ResultSet rs = stmt.executeQuery("SELECT * FROM  t_news");
            response.setContentType("text/html;charSet=utf-8");
            //获取页面输出流
            PrintStream out = new PrintStream(response.getOutputStream());
            //输出HTML标签
            out.println("<html>");
            out.println("<head>");
            out.println("<title>访问servlet初始化参数测试</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<table bgcolor=\"#9999dd\" border=\"1\" width=\"480\">");
            //遍历结果集
            while (rs.next()) {
                //输出结果集
                out.println("<tr>");
                out.println("<td>" + rs.getString(1) + "</td>");
                out.println("<td>" + rs.getString(2) + "</td>");
                out.println("</tr>");
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
        }
}
